<template>
    <div class="container">
        <el-form ref="form" :model="form" label-width="80px">
            <el-row>
                <el-col :span="5" style="min-width: 230px">
                    <div class="container" style="min-height: 300px">
                        <el-tabs v-model="activeName" @tab-click="handleClick">
                            <el-tab-pane label="组织架构" name="组织架构">
                                <!-- <div style="margin-top: 10px; font-size: 14px; cursor: pointer" @click="all">{{ sjname }}</div> -->
                                <el-tree @node-click="handleNodeClick" default-expand-all :data="data" :props="customProps"> </el-tree>
                            </el-tab-pane>
                            <el-tab-pane label="员工" name="员工">
                                <el-input
                                    style="border-radius: 0 5px 5px 0; font-size: 8px"
                                    placeholder="请输入关键字"
                                    @change="searchstaff"
                                    v-model="searchName"
                                >
                                    <el-button slot="append" @click="handleSearch">搜索</el-button>
                                </el-input>
                                <div class="staffcontent">
                                    <div
                                        class="staffuser"
                                        :class="{ active: index == isActive }"
                                        v-for="(item, index) in userList"
                                        @click="handlestaff(index)"
                                        :key="index"
                                    >
                                        <span class="name-circle" style="color:white;" :class="{ activeone: index == isActive }">{{ item.username }}</span>
                                        <span style="margin-left: 20px">{{ item.name }}</span>
                                        <span style="float: right">{{ item.phone }}</span>
                                    </div>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-col>
                <el-col :span="18" style="margin-left: 10px">
                    <div class="container" style="min-height: 70%">
                        <h3>{{ name }}</h3>
                        <el-tabs v-model="activetabs">
                            <el-tab-pane
                                v-for="(item, index) in companyPermissionList"
                                :key="index"
                                :label="item.appName"
                                :name="item.appName"
                            >
                                <div style="display: flex; color: #606266; margin-bottom: 10px">
                                    <el-button @click="changeJurisdiction" :class="[changeJurisdictions ? '' : 'activess']"
                                        >功能权限</el-button
                                    >
                                    <el-button @click="changeJurisdiction1" :class="[changeJurisdictions ? 'activess' : '']"
                                        >系统权限</el-button
                                    >
                                </div>
                                <el-checkbox-group v-model="checked" style="margin-top:20px;" >
                                <div v-for="(item, zindex) in item.permissionList" :key="zindex">
                                    <div class="checkbox-content" v-if="item.configMenu == changeJurisdictions">
                                        <el-checkbox
                                            v-model="item.id"
                                            :label="item.id"
                                            @change="(checke) => changeAll(checke, item)"
                                            >{{ item.name }}</el-checkbox
                                        >
                                        <el-checkbox-group
                                            v-model="checked"
                                            class="checked-right"
                                            style="margin-top: 20px; display: inline-block"
                                        >
                                            <el-checkbox
                                                v-for="(s, sindex) in item.children"
                                                @change="handlecheckbox(item)"
                                                :key="sindex"
                                                :label="s.id"
                                                >{{ s.name }}</el-checkbox
                                            >
                                        </el-checkbox-group>
                                    </div>
                                </div>
                                </el-checkbox-group>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-col>
            </el-row>
            <el-form-item class="footerFixed" v-if="added" label-width="0px" style="z-index: 2000">
                <el-button type="primary" @click="menu_save">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { resource_company_appMenus, resource_user_appMenus, resource_set_appMenus } from '@/request/breedApi';
import { user_findByAll, company_findById, staffuser_findByAll,department_bindresource,department_loadresource } from '@/request/api';
export default {
    inject: ['reload'],
    data() {
        return {
            activeName: '组织架构',
            isActive: -1,
            changeJurisdictions: false,
            companyPermissionList: [],
            num: '',
            ifshow: false,
            added: true,
            activetabs: '',
            userList: '',
            searchName: '',
            form: {},
            disabled: true,
            list: [],
            checked: [],
            checkeds: [],
            shangji: '',
            bumen: '',
            defaultProps: {
                children: '',
                label: 'label'
            },
            tableData: [],
            data: [],
            isShow: true,
            delid: '',
            departmentId: '',
            customProps: {
                label: 'name',
                children: 'children',
                id: 'id'
            },
            userid: '',
            name: '',
            sjname: ''
        };
    },
    mounted() {
        this.init();
        this.init1();
        this.init2();
    },
    created() {},
    methods: {
        //组织架构部门权限
        handleNodeClick(e) {
            console.log(e)
            this.name = e.name;
			this.departmentId = e.id
			var id = localStorage.getItem('companyId');
            
            this.checked = [];
			if(this.departmentId == id){
                this.checked = []
			}else{
				department_loadresource(this.departmentId).then((res)=>{
					var userPermissionList = res.data;
					for (var i = 0; i < userPermissionList.length; i++) {
						for (var s = 0; s < userPermissionList[i].menus.length; s++) {
							if (userPermissionList[i].menus[s].checked == true) {
								this.checked.push(userPermissionList[i].menus[s].id)
								if (userPermissionList[i].menus[s].children != null){
									for (var j = 0; j < userPermissionList[i].menus[s].children.length; j++){
										if(userPermissionList[i].menus[s].children[j].checked == true){
											this.checked.push(userPermissionList[i].menus[s].children[j].id);
										}
									}
								}
							}
						}
					}
				})
			}
        },
        changeJurisdiction() {
            this.changeJurisdictions = false;
        },
        changeJurisdiction1() {
            this.changeJurisdictions = true;
        },
        // 选择父级权限
        changeAll(checke, item) {
            if (checke == true) {
                let checkedAll = this.checked;
                if (checkedAll.length != 0) {
                    var arr1 = this.checked;
                    var arr2 = [];
                    arr2.push(item.id);
                    if (item.children != null) {
                        for (var i = 0; i < item.children.length; i++) {
                            arr2.push(item.children[i].id);
                        }
                    }
                    var arr3 = arr1.concat(arr2);
                    var arr4 = [];
                    for (var i = 0; i < arr3.length; i++) {
                        if (arr4.indexOf(arr3[i]) === -1) {
                            arr4.push(arr3[i]);
                        }
                    }
                    this.checked = arr4;
                } else {
                    this.checked.push(item.id);
                    if (item.children != null) {
                        // this.checked.push(item)
                        for (var i = 0; i < item.children.length; i++) {
                            this.checked.push(item.children[i].id);
                        }
                    }
                }
            } else {
                var arr1 = this.checked;
                var arr2 = [];
                var arr3 = [];
                if (item.children != null) {
                    for (var s = 0; s < arr1.length; s++) {
                        var flag = false;
                        for (var i = 0; i < item.children.length; i++) {
                            if (arr1[s] == item.children[i].id) {
                                flag = true;
                            }
                        }
                        if (flag == false) {
                            arr2.push(arr1[s]);
                        }
                    }
                    for (var j = 0; j < arr2.length; j++) {
                        if (arr2[j] != item.id) {
                            arr3.push(arr2[j]);
                        }
                    }
                } else {
                    for (var j = 0; j < arr1.length; j++) {
                        if (arr1[j] != item.id) {
                            arr3.push(arr1[j]);
                        }
                    }
                }
                this.checked = arr3;
            }
        },
        // 点击员工 回显 员工的权限
        handlestaff(index) {
            this.isActive = index;
            this.userid = this.userList[index].id;
            this.name = this.userList[index].name;
            this.checked = [];
            resource_user_appMenus(this.userList[index].id).then((res) => {
                var userPermissionList = res.data;
                for (var i = 0; i < userPermissionList.length; i++) {
                    for (var s = 0; s < userPermissionList[i].menus.length; s++) {
                        if (userPermissionList[i].menus[s].checked == true) {
                            this.checked.push(userPermissionList[i].menus[s].id)
                            if (userPermissionList[i].menus[s].children != null){
                                for (var j = 0; j < userPermissionList[i].menus[s].children.length; j++){
                                    if(userPermissionList[i].menus[s].children[j].checked == true){
                                        this.checked.push(userPermissionList[i].menus[s].children[j].id);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        },
        handleClick() {},
        // 选择单个权限
        handlecheckbox(item) {
            this.checked.push(item.id)
        },
        // change 触发搜索
        searchstaff() {
            this.init();
        },
        // 点击搜索员工
        handleSearch() {
            this.init();
        },

        // 获取所有的员工
        init() {
            user_findByAll('?name=' + this.searchName).then((res) => {
                this.userList = res.data;
                for (let i = 0; i < this.userList.length; i++) {
                    this.userList[i].username = this.userList[i].name.substring(0, 1);
                }
            });
        },
        // 根据 公司id 获取 所有的权限
        init1() {
			this.companyPermissionList = []
            let id = localStorage.getItem('ms_id');
            resource_user_appMenus(id).then((res) => {
				var r = JSON.parse(localStorage.getItem("userInfo"))
				var s = r.userInfo.userType
				if(s == "GOV"){
					
					for(var i = 0;i<res.data.length;i++){
						if(res.data[i].appId == "001"){
							this.companyPermissionList.push(res.data[i])
						}
					}
				}else{
					this.companyPermissionList = res.data;
				}
               // console.log(this.companyPermissionList)
                this.activetabs = res.data[0].appName;
                for (var i = 0; i < this.companyPermissionList.length; i++) {
					
					 
                    this.companyPermissionList[i].permissionList = this.companyPermissionList[i].menus;
					// console.log( this.companyPermissionList)
                }
            });
        },
        // 根据 公司id 获取 所有的部门
        init2() {
            var id = localStorage.getItem('companyId');
            company_findById(id).then((res) => {
                this.data.push({ id: res.data.id, name: res.data.abbreviation, children: [] });
                this.bumen = res.data.name; 
                this.departmentId = res.data.id;
                staffuser_findByAll('').then((res) => {
                    this.data[0].children = res.data;
                });
            });
        },
        // 权限保存
        menu_save() {
            var arr = [];
			var list = []
			var list1 = []
			for(var i=0;i<this.companyPermissionList.length;i++){
				for(var k=0;k<this.companyPermissionList[i].menus.length;k++){
					// if()
					for(var s=0;s<this.checked.length;s++){
						if(this.checked[s] == this.companyPermissionList[i].menus[k].id){
							list.push({appId:this.companyPermissionList[i].menus[k].appId,resourceId:this.checked[s]})
							list1.push({appId:this.companyPermissionList[i].menus[k].appId,id:this.checked[s]})
						}
					}
					if(this.companyPermissionList[i].menus[k].children != "" && this.companyPermissionList[i].menus[k].children != null){
						for(var r=0;r<this.companyPermissionList[i].menus[k].children.length;r++){
							for(var s=0;s<this.checked.length;s++){
								if(this.checked[s] == this.companyPermissionList[i].menus[k].children[r].id){
									list.push({appId:this.companyPermissionList[i].menus[k].children[r].appId,resourceId:this.checked[s]})
									list1.push({appId:this.companyPermissionList[i].menus[k].children[r].appId,id:this.checked[s]})
								}
							}
						}
					}
				}
			}
		
            this.$confirm('是否确认提交', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
				if(this.activeName == "组织架构"){
					let data = {
						departmentId: this.departmentId,
						menus: list1
					};
					department_bindresource(data).then((res)=>{
						this.$notify({
							title: '提示',
							message: '保存成功',
							type: 'success',
							duration: 1000
						});
					})
					
				}else{
					let data = {
						userId: this.userid,
						menus: list
					};
					
					resource_set_appMenus(data).then((res) => {
						this.$notify({
							title: '提示',
							message: '保存成功',
							type: 'success',
							duration: 1000
						});
					});
				}
                
                this.init();
                this.init1();
            });
        },
        // all() {
        //     this.bumen = this.sjname;
        //     this.ifshow = false;
        //     let data = {
        //         page: this.currentPage
        //     };
            // staffuser_findByList(data).then((res)=>{
            //     this.tableData = res.rows

            // 	res.rows.forEach(v => {
            // 		v.checked = true
            // 	});
            // 	res.companyCount.checked = false
            // 	this.tableData.unshift(res.companyCount)
            // 	this.total = res.total + 1
            //     var _this = this
            //     for (let i = 0; i < this.tableData.length; i++) {
            //         if(this.tableData[i].state == 0){
            //             _this.tableData[i].stateful = "启用"
            //         }else{
            //             _this.tableData[i].stateful = "禁用"
            //         }

            //     }
            // })
        // }
    }
};
</script>

<style scoped>
.active {
    background: #cceeff;
}
.activess {
    color: #409eff;
}
.activeone {
    background: #33ccff !important;
}
.name-circle {
    width: 25px;
    line-height: 25px;
    text-align: center;
    height: 25px;
    border-radius: 50%;
    background: #909399;
    display: inline-block;
}
.staffuser {
    font-size: 12px;
    height: 35px;
    line-height: 35px;
    cursor: pointer;
}
.staffcontent {
    margin-top: 20px;
    height: 300px;
    overflow-y: auto;
}
.checked-right {
    position: absolute;
    left: 150px;
    top: -12px;
}
.checkbox-content {
    height: 30px;
    line-height: 30px;
    position: relative;
    border: 1px solid #dcdfe6;
    padding: 8px;
}
.el-row {
    margin-bottom: 20px;
}
.el-pagination {
    text-align: center;
}
.el-select .el-input {
    width: 130px;
}
.input-with-select .el-input-group__prepend {
    background-color: #fff;
}
.el-input--small .el-input__inner {
    border-radius: 5px 0 0 5px !important;
    border-right: none;
}
</style>